/**
 * Copyright &copy; 2012-2013 All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 */
package com.neusoft.lohas.modules.ivm.utils;

import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.UnavailableSecurityManagerException;
import org.apache.shiro.session.InvalidSessionException;
import org.apache.shiro.subject.Subject;

import com.google.common.collect.Maps;
import com.neusoft.lohas.common.service.BaseService;
import com.neusoft.lohas.common.utils.SpringContextHolder;
import com.neusoft.lohas.modules.ivm.dao.merchant.MerchantDao;
import com.neusoft.lohas.modules.ivm.entity.merchant.Merchant;
import com.neusoft.lohas.modules.sys.security.SystemAuthorizingRealm.Principal;
import com.neusoft.lohas.modules.sys.utils.UserUtils;

/**
 * 商户工具类
 * @author jackie.liu
 * @version 2014-11-13
 */
public class MerchantUtils extends BaseService {

	private static MerchantDao merchantDao = SpringContextHolder.getBean(MerchantDao.class);

	public static final String CACHE_MERCHANT = "merchant";
	
	public static Merchant getMerchant(){
		Merchant merchant = (Merchant)getCache(CACHE_MERCHANT);
		if(merchant==null || StringUtils.isBlank(merchant.getId())) {
			// 缓存商户信息
			merchant = merchantDao.findByCreateBy(UserUtils.getUser().getId());
			if (merchant!=null && StringUtils.isNotBlank(merchant.getId())){
				MerchantUtils.putCache(MerchantUtils.CACHE_MERCHANT, merchant);
			}else {
				merchant = new Merchant();
			}
		}
		return merchant;
	}
	
	public static Merchant getMerchantById(String id){
		if(StringUtils.isNotBlank(id)) {
			return merchantDao.get(id);
		} else {
			return null;
		}
	}
	
	// ============== User Cache ==============
	
	public static Object getCache(String key) {
		return getCache(key, null);
	}
	
	public static Object getCache(String key, Object defaultValue) {
		Object obj = getCacheMap().get(key);
		return obj==null?defaultValue:obj;
	}

	public static void putCache(String key, Object value) {
		getCacheMap().put(key, value);
	}

	public static void removeCache(String key) {
		getCacheMap().remove(key);
	}
	
	public static Map<String, Object> getCacheMap(){
		Map<String, Object> map = Maps.newHashMap();
		try{
			Subject subject = SecurityUtils.getSubject();
			Principal principal = (Principal)subject.getPrincipal();
			return principal!=null?principal.getCacheMap():map;
		}catch (UnavailableSecurityManagerException e) {
			
		}catch (InvalidSessionException e){
			
		}
		return map;
	}
	
}
